from django.shortcuts import render,HttpResponse,redirect
from .models import *
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
# Create your views here.


def index(request):
    return HttpResponse('ok')

def adduser(request):
    if request.method == 'GET':
        listl = TYPE.objects.all()
        return render(request,'adduser.html',{'listl':listl})
    if request.method == 'POST':
        truename = request.POST.get('truename')
        pwd = request.POST.get('pwd')
        tel = request.POST.get('tel')
        sex = request.POST.get('sex')
        eid = request.POST.get('eid')
        address = request.POST.get('address')
        uname = request.POST.get('uname')
        Users.objects.create(
            truename=truename,
            pwd=pwd,tel=tel,
            sex=sex,
            eid_id=eid,
            address=address,
            uname=uname
            )
    return HttpResponse('新增成功')

def register(request):
    if request.method == 'GET':
        return render(request,'register.html')
    if request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        User.objects.create_user(username=name,password=password)
        return HttpResponse('注册成功')

def loginx(request):
    if request.method == 'GET':
        return render(request,'loginx.html')
    if request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        user = authenticate(username=name,password=password)
        if user:
            login(request,user=user)
            return redirect('app1:showuser')
        return HttpResponse('登录失败')

def showuser(request):
    user1 = Users.objects.all()
    uname=request.POST.get('uname')
    address=request.POST.get('address')
    print(address)
    print(uname)
    if request.method == 'POST':
        user1 = Users.objects.filter(uname__contains=uname)
        return render(request,'showuser.html',{'user1':user1})
    return render(request,'showuser.html',{'user1':user1})

def deluser(request,id):
    Users.objects.filter(id=id).delete()
    return redirect('app1:showuser')

def update(request,uid):
    listl = TYPE.objects.all()
    if request.method == 'POST':
        id = request.POST.get('id')
        truename = request.POST.get('truename')
        pwd = request.POST.get('pwd')
        tel = request.POST.get('tel')
        sex = request.POST.get('sex')
        eid = request.POST.get('eid')
        address = request.POST.get('address')
        uname = request.POST.get('uname')
        Users.objects.filter(id=id).update(
            truename=truename,
            pwd=pwd,
            tel=tel,
            sex=sex,
            eid=eid,
            address=address,
            uname=uname
        )
        return redirect('app1:showuser')
    date = Users.objects.filter(id=uid)
    return render(request,'update.html',{'date':date,'listl':listl})